﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Torch.WL.Web;
using Torch.WL.Business;
using Torch.FrameWork.Utility;
using Torch.WL.Entity;
using System.Web.UI.HtmlControls;
namespace Torch.WL.Web.Admin.Modubles
{
    public partial class UserGrant : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            strinfo.InnerHtml = "";
            strinfo.Visible = false;

            if (!IsPostBack)
            {
                UserHandle.InitModule("admin_ListUsers");
                if (!UserHandle.ValidationHandle(PermissionTag.Grant))
                {
                    GotoErrPage("无权限!");
                }
                else
                {
                    btn_saverole.Attributes.Add("OnClick", "getdata()");
                    if (Request.QueryString["uid"] != null && Request.QueryString["name"] != null)
                    {
                        UNAME.Text = Request.QueryString["name"].ToString();
                        UID.Text = Request.QueryString["uid"].ToString();
                        BindModuleType();
                        RolePanel.Visible = false;
                    }
                }
                
            }
        }

        int UserID
        {
            get
            {
                return int.Parse(UID.Text);
            }
        }
        
        protected void BindModuleType()
        {
            ModuleLogic MTbll = new ModuleLogic();
            DataSet ds = MTbll.GetModuleTypeList("");
            ModuleTypeView.DataSource = ds;
            ModuleTypeView.DataBind();
        }

        
        protected void BindModules()
        {
            if (TID.Text != "")
            {
                ModuleLogic Mbll = new ModuleLogic();
                DataSet ds = Mbll.GetModuleList2(TID.Text);
                ModuleView.DataSource = ds;
                ModuleView.DataBind();

                if (ds.Tables[0].Rows.Count == 0)
                {
                    btn_AllSave.Visible = false;
                    btnAllStandard.Visible = false;
                }
                else
                {
                    btn_AllSave.Visible = true;
                    btnAllStandard.Visible = true;
                }
            }
            else
            {
                btn_AllSave.Visible = false;
                btnAllStandard.Visible = false;
                ModuleView.DataSource = null;
                ModuleView.DataBind();
            }
        }

        protected void BindRole()
        {
            UserLogic bll = new UserLogic();
            RoleList.Items.Clear();
            ArrayList rid = bll.GetUserRoleArray(int.Parse(UID.Text));
            string strwhere = "";
            for (int i = 0; i < rid.Count; i++)
            {
                string[] r = rid[i].ToString().Split(',');
                RoleList.Items.Add(new ListItem(r[1], r[0]));
                strwhere += r[0] + ",";
            }
            if (strwhere != "")
            {
                OldRoleList.Text = strwhere.Substring(0, strwhere.Length - 1);
                strwhere = "not RoleID in(" + OldRoleList.Text + ")";
            }

            RoleLogic bll2 = new RoleLogic();
            FromRoleList.DataSource = bll2.GetRoleList(strwhere, "");
            FromRoleList.DataTextField = "RoleName";
            FromRoleList.DataValueField = "RoleID";
            FromRoleList.DataBind();
        }

        protected void ModuleType_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditView")
            {
                TID.Text = e.CommandArgument.ToString();
                BindModules();
            }
        }

        protected void ModuleView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                AuthorityDirLogic AD = new AuthorityDirLogic();
                ModuleLogic Modulebll = new ModuleLogic();
                RoleLogic Rolebll = new RoleLogic();

                Repeater rptAuthrityList = (Repeater)e.Row.FindControl("rptAuthrityList");
                Label lab_ID = (Label)e.Row.FindControl("lab_ID");
                Label lab_Verify = (Label)e.Row.FindControl("lab_Verify");

                ////取该模块的权限列表, 不把所有权限取出来
                //DataSet ds = AD.GetAuthorityList("", "order by AuthorityOrder asc");
                DataSet ds = Modulebll.GetAuthorityNameList(int.Parse(lab_ID.Text));
                DataSet MALDS = Modulebll.GetAuthorityList(int.Parse(lab_ID.Text));

                UserLogic userLogic = new UserLogic();

                UserEntity model = userLogic.GetUserModel(UserID);

                if (null == model) { return; }

                UserSession user = null;
                if (model.RoleID.Count != 0 || model.IsLimit == true)
                {
                    if (model.Status != 0)
                    {
                        user = new UserSession(model.UserID, model.UserName, model.RoleID, model.UserGroup, model.IsLimit, model.Status);
                    }
                }
                ArrayList ModuleList = null;
                ArrayList UserAuthorityList = UserHandle.GetUserModuleAuthorityList(user,
                                                                        (e.Row.FindControl("hidModuleTag") as HtmlInputHidden).Value,
                                                                        out ModuleList
                                                                        );


                DataTable dtTypeNameList = ds.Tables[0].DefaultView.ToTable(true, "TypeName");
                rptAuthrityList.DataSource = dtTypeNameList;
                rptAuthrityList.DataBind();

                int n = ds.Tables[0].Rows.Count;//系统权限个数
                string[] vstate = new string[n];

                int nowPos = 0;

                for (int j = 0; j < rptAuthrityList.Items.Count; j++)
                {
                    CheckBoxList AuthorityList_Grant = (CheckBoxList)rptAuthrityList.Items[j].FindControl("AuthorityList_Grant");
                    Literal ltlTypeName = (Literal)rptAuthrityList.Items[j].FindControl("ltlTypeName");
                    AuthorityList_Grant.Items.Clear();

                    DataRow[] drsByTypeName = ds.Tables[0].Select(string.Format("TypeName='{0}'", ltlTypeName.Text.Trim()));

                    //获取系统配置的权限列表，如果模块没有该权限，则禁用该权限
                    for (int i = 0; i < drsByTypeName.Length; i++)
                    {
                        AuthorityList_Grant.Items.Add(new ListItem(drsByTypeName[i]["AuthorityName"].ToString(), drsByTypeName[i]["AuthorityTag"].ToString()));
                        AuthorityList_Grant.Items[i].Enabled = false;

                        if (MALDS.Tables[0].Select(string.Format("AuthorityTag='{0}'", drsByTypeName[i]["AuthorityTag"].ToString())).Length > 0)
                        {
                            AuthorityList_Grant.Items[i].Enabled = true;
                        }
                        vstate[nowPos + i] = "0";//初始状态数组; 未选中
                    }

                    AuthorityList_Grant.DataBind();

                    //将模块权限付值
                    for (int l = 0; l < AuthorityList_Grant.Items.Count; l++)
                    {
                        if (Contains(UserAuthorityList, AuthorityList_Grant.Items[l].Value))
                        {
                            if (AuthorityList_Grant.Items[l].Enabled)
                                vstate[nowPos + l] = "1";//选中

                            //权限允许
                            AuthorityList_Grant.Items[l].Selected = true;
                        }
                    }

                    nowPos += drsByTypeName.Length - 1;
                }

                lab_Verify.Text = TypeParse.StringArrayToString(vstate, ',');
            }
        }
        bool Contains(IList list, string tag)
        {
            return list.Contains(tag.ToUpper());
        }

        protected void ModuleView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            ArrayList list = new ArrayList();//建立事务列表
            RoleLogic Rolebll = new RoleLogic();
            Label lab_Verify = (Label)this.ModuleView.Rows[e.NewSelectedIndex].Cells[0].FindControl("lab_Verify");
            string[] vstate = lab_Verify.Text.Split(',');//获取原始状态

            Repeater rptAuthrityList = (Repeater)this.ModuleView.Rows[e.NewSelectedIndex].FindControl("rptAuthrityList");

            int nowPos = 0;

            for (int j = 0; j < rptAuthrityList.Items.Count; j++)
            {
                CheckBoxList calg = (CheckBoxList)rptAuthrityList.Items[j].FindControl("AuthorityList_Grant");

                for (int i = 0; i < calg.Items.Count; i++)
                {
                    if (calg.Items[i].Enabled)
                    {
                        if (calg.Items[i].Selected)
                        {
                            if (vstate[i + nowPos] != "1")//检查数据有没有变化
                            {
                                string item = string.Empty;
                                item = item + UID.Text + "|"
                                    + this.ModuleView.DataKeys[e.NewSelectedIndex].Values[0].ToString() + "|"
                                    + calg.Items[i].Value + "|1";//设置为1，加入允许权限
                                list.Add(item);
                            }
                        }
                        else
                        {
                            if (vstate[i + nowPos] != "0")//检查数据有没有变化
                            {
                                string item = string.Empty;
                                item = item + UID.Text + "|"
                                    + this.ModuleView.DataKeys[e.NewSelectedIndex].Values[0].ToString() + "|"
                                    + calg.Items[i].Value + "|0";//设置为0，加入禁止权限
                                list.Add(item);
                            }
                        }

                    }
                }

                nowPos += calg.Items.Count - 1;
            }

            if (Rolebll.UpdateUserAuthority(list))
            {
                BindModules();
                ShowMsg(true, "更新成功！");
            }
            else
            {
                ShowMsg(true, "更新失败！");
            }
           
        }

        protected void btn_AllSave_Click(object sender, EventArgs e)
        {
            RoleLogic Rolebll = new RoleLogic();

            ArrayList list = new ArrayList();//建立事务列表
            for (int i = 0; i <= ModuleView.Rows.Count - 1; i++)
            {
                Label lab_Verify = (Label)this.ModuleView.Rows[i].Cells[0].FindControl("lab_Verify");
                string[] vstate = lab_Verify.Text.Split(',');//获取原始状态

                Repeater rptAuthrityList = (Repeater)this.ModuleView.Rows[i].FindControl("rptAuthrityList");

                int nowPos = 0;

                for (int jj = 0; jj < rptAuthrityList.Items.Count; jj++)
                {
                    CheckBoxList calg = (CheckBoxList)rptAuthrityList.Items[jj].FindControl("AuthorityList_Grant");

                    for (int j = 0; j < calg.Items.Count; j++)
                    {
                        if (calg.Items[j].Selected)
                        {
                            if (vstate[j + nowPos] != "1")//检查数据有没有变化
                            {
                                string item = string.Empty;
                                item = item + UID.Text + "|"
                                    + this.ModuleView.DataKeys[i].Values[0].ToString() + "|"
                                    + calg.Items[j].Value + "|1";//设置为1，加入允许权限
                                list.Add(item);
                            }
                        }
                        else
                        {
                            if (vstate[j + nowPos] != "0")//检查数据有没有变化
                            {
                                string item = string.Empty;
                                item = item + UID.Text + "|"
                                    + this.ModuleView.DataKeys[i].Values[0].ToString() + "|"
                                    + calg.Items[j].Value + "|0";//设置为0，加入禁止权限
                                list.Add(item);
                            }
                        }
                    }

                    nowPos += calg.Items.Count - 1;

                }
            }

            if (Rolebll.UpdateUserAuthority(list))
            {
                BindModules();
                ShowMsg(true, "设置成功！");
            }
            else
            {
                ShowMsg(true, "设置操作失败！");
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DropDownList1.SelectedIndex == 0)
            {
                ModelPanel.Visible = true;
                RolePanel.Visible = false;
            }
            else
            {
                BindRole();
                ModelPanel.Visible = false;
                RolePanel.Visible = true;
            }
        }

        protected void btn_saverole_Click(object sender, EventArgs e)
        {
            string s = Request.Form["TRoleList"].ToString();

            UserLogic bll = new UserLogic();
            ArrayList ar = new ArrayList();//加加表
            ArrayList dr = new ArrayList();//删除表

            if (s != "")
            {
                string[] str = s.Substring(0, s.Length - 1).Split(',');
                string[] ostr = OldRoleList.Text.ToString().Split(',');
                for (int i = 0; i < str.Length; i++)
                {
                    if (!TypeParse.IsStringArray(str[i], ostr))
                    {
                        //不存在则添加到插入记录列表
                        ar.Add(UID.Text + "," + str[i]);
                    }
                }

                for (int i = 0; i < ostr.Length; i++)
                {
                    if (!TypeParse.IsStringArray(ostr[i], str))
                    {
                        //不存在则添加到删除记录列表
                        dr.Add(UID.Text + "," + ostr[i]);
                    }
                }
            }
            else
            {
                //如果提交角色为空则删除该用户的所有角色
                string[] ostr = OldRoleList.Text.ToString().Split(',');
                for (int i = 0; i < ostr.Length; i++)
                {
                    //不存在则添加到删除记录列表
                    dr.Add(UID.Text + "," + ostr[i]);
                }
            }

            try
            {
                if (ar.Count != 0) { bll.addUserRole(ar); }
                if (dr.Count != 0) { bll.DeleteUserRole(dr); }
                BindRole();
            }
            catch
            { }
        }

        protected void ModuleView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Standard")
            {

                GridViewRow gvr = ModuleView.Rows[int.Parse(e.CommandArgument.ToString())];
                int moduleId = int.Parse(ModuleView.DataKeys[int.Parse(e.CommandArgument.ToString())].Values[0].ToString());
                ModuleLogic Modulebll = new ModuleLogic();

                Modulebll.DeleteGrantUserAuthority(UserID, moduleId);

                ModuleView_RowDataBound(null, new GridViewRowEventArgs(gvr));

                strinfo.InnerHtml = JScript.errinfo("恢复标准成功！");
                strinfo.Visible = true;

            }
        }

        protected void btnAllStandard_Click(object sender, EventArgs e)
        {
            for (int i = 0; i <= ModuleView.Rows.Count - 1; i++)
            {
                GridViewRow gvr = ModuleView.Rows[i];
                int moduleId = int.Parse(ModuleView.DataKeys[i].Values[0].ToString());
                ModuleLogic Modulebll = new ModuleLogic();

                Modulebll.DeleteGrantUserAuthority(UserID, moduleId);

                ModuleView_RowDataBound(null, new GridViewRowEventArgs(gvr));

            }

            strinfo.InnerHtml = JScript.errinfo("全部恢复到标准权限！");
            strinfo.Visible = true;


        }

        void ShowMsg(bool success, string msg)
        {
            strinfo.InnerHtml = msg;
            strinfo.Attributes["class"] = success ? "w_info" : "w_error";
            strinfo.Visible = true;
        }

    }
}
